package com.lg.wechat.handler;

import java.lang.reflect.InvocationTargetException;
import java.util.Date;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import com.lg.utils.StringUtils;
import com.lg.wechat.builder.TextBuilder;
import com.lg.wechat.business.wxuser.entity.WxUser;
import com.lg.wechat.business.wxuser.service.WxUserService;
import com.lg.wechat.common.annotation.Clear;

import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.result.WxMpUser;

/**
 * @author Binary Wang(https://github.com/binarywang)
 */
@Component
@Clear
public class SubscribeHandler extends AbstractHandler {

  @Autowired
  WxUserService wxUserService;
	
  @Override
  public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage,
                                  Map<String, Object> context, WxMpService weixinService,
                                  WxSessionManager sessionManager) throws WxErrorException {

    this.logger.info("新关注用户 OPENID: " + wxMessage.getFromUser());
    // 获取微信用户基本信息
    WxMpUser userWxInfo = weixinService.getUserService().userInfo(wxMessage.getFromUser(), null);
    if (userWxInfo != null) {
    	WxUser wxUser=wxUserService.selectByOpenId(userWxInfo.getOpenId());
    	if(wxUser==null){
    		wxUser=new WxUser();
    		try {
				BeanUtils.copyProperties(wxUser, userWxInfo);
			} catch (IllegalAccessException | InvocationTargetException e) {
				e.printStackTrace();
			}
    		wxUser.setSubscribeTime(new Date());
    		wxUser.setSubscribe(userWxInfo.getSubscribe()?0:1);
    		wxUserService.save(wxUser);
    	}else{
    		wxUser.setSubscribe(userWxInfo.getSubscribe()?0:1);
    		wxUserService.updateById(wxUser);
    	}
    }

    WxMpXmlOutMessage responseResult = null;
    try {
        if(StringUtils.isNotEmpty(wxMessage.getEventKey())){//参数二维码单独处理业务
        	responseResult = handleSpecial(wxMessage);
    	}
    } catch (Exception e) {
      this.logger.error(e.getMessage(), e);
    }

    if (responseResult != null) {
      return responseResult;
    }

    try {
      return new TextBuilder().build("感谢关注", wxMessage, weixinService);
    } catch (Exception e) {
      this.logger.error(e.getMessage(), e);
    }

    return null;
  }

  /**
   * 处理特殊请求，比如如果是扫码进来的，可以做相应处理
   */
  private WxMpXmlOutMessage handleSpecial(WxMpXmlMessage wxMessage)
      throws Exception {
    logger.info("微信扫码"+wxMessage.getEventKey());
    return null;
  }

}
